/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 *
 *
 *
 */
package rad.framework.jaxws;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.jboss.seam.core.ConversationPropagation;
import org.jboss.seam.core.Manager;
import org.jboss.seam.log.LogProvider;
import org.jboss.seam.log.Logging;
import org.jboss.seam.webservice.SOAPRequestHandler;

/**
 * This client handler works in conjunction with the Seam server-side handler
 * (org.jboss.seam.webservice.SOAPRequestHandler) to managing conversation
 * propagation.
 * 
 * @author boudyacho
 */
public class SeamClientHandler implements SOAPHandler<SOAPMessageContext> {

	private static final LogProvider log = Logging
			.getLogProvider(SeamClientHandler.class);

	private Set<QName> headers = new HashSet<QName>();

	private String handlerName;

	/**
	 * Handle inbound and outbound messages
	 */
	public boolean handleMessage(SOAPMessageContext msgContext) {
		Boolean outbound = (Boolean) msgContext
				.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		if (outbound == null)
			throw new IllegalStateException("Cannot obtain required property: "
					+ MessageContext.MESSAGE_OUTBOUND_PROPERTY);

		return outbound ? handleOutbound(msgContext)
				: handleInbound(msgContext);
	}

	/**
	 * Sets the conversation ID in the outbound SOAP message.
	 */
	public boolean handleOutbound(SOAPMessageContext smc) {
		try {
			String conversationId = Manager.instance()
					.getCurrentConversationId();
			if (conversationId != null) {
				SOAPHeader header = smc.getMessage().getSOAPHeader();
				if (header != null) {
					SOAPElement element = header
							.addChildElement(SOAPRequestHandler.CIDQN);
					element.addTextNode(conversationId);
					smc.getMessage().saveChanges();
				}
			}

			return true;
		} catch (SOAPException ex) {
			log.error("Exception processing outbound message", ex);
			return false;
		}
	}

	public boolean handleInbound(SOAPMessageContext smc) {
		try {
			String conversationId = Manager.instance()
					.getCurrentConversationId();

			String inboundConversationId = extractConversationId(smc);
			ConversationPropagation.instance()
					.setConversationId(conversationId);

			if (!conversationId.equals(inboundConversationId)) {
				log.error("Inbound conversation Id: " + inboundConversationId
						+ " do not match current conversation id: "
						+ conversationId);
				return false;
			}
			return true;
		} catch (SOAPException ex) {
			log.error("Error handling inbound SOAP request", ex);
			return false;
		}
	}

	/**
	 * Extracts the conversation ID from an incoming SOAP message
	 */
	private String extractConversationId(SOAPMessageContext smc)
			throws SOAPException {
		SOAPHeader header = smc.getMessage().getSOAPHeader();

		if (header != null) {
			Iterator iter = header.getChildElements(SOAPRequestHandler.CIDQN);
			if (iter.hasNext()) {
				SOAPElement element = (SOAPElement) iter.next();
				return element.getFirstChild().getNodeValue();
			}
		}

		return null;
	}

	public boolean handleFault(SOAPMessageContext messagecontext) {
		return true;
	}

	public void close(MessageContext messageContext) {
	}

	public Set<QName> getHeaders() {
		return headers;
	}

	public void setHeaders(Set<QName> headers) {
		this.headers = headers;
	}

	public String getHandlerName() {
		return handlerName;
	}

	public void setHandlerName(String handlerName) {
		this.handlerName = handlerName;
	}

	@Override
	public String toString() {
		return (handlerName != null ? handlerName : super.toString());
	}
}
